package sfin.controller;

import sfin.service.BancoService;
import sfin.swt.exception.StatizoException;
import br.com.statizo.financeiro.domain.entity.impl.Banco;

public class BancoController {

	private BancoService bancoService;
	private int selectedIndex = -1;
	
	private String codigo;
	private String nome;
	
	public BancoController(BancoService bancoService) {
		this.bancoService = bancoService;
	}
	
	
	public void callDel() throws StatizoException{
		bancoService.remove(selectedIndex);
		if(this.existeBanco()){
			selectFirst();
		}else{
			clearSelection();			
		}

		loadData();
	}
	
	public void callSave() throws StatizoException{
		selectedIndex = bancoService.save(selectedIndex,codigo, nome);
	}
	
	protected void loadData(){
		if(selectedIndex != -1){
			Banco banco = bancoService.getAt(selectedIndex);
			codigo = banco.getCodigo();
			nome = banco.getNome();
		}else{
			codigo = "";
			nome = "";
		}
	}
	
	public void setBancoService(BancoService bancoService) {
		this.bancoService = bancoService;
	}
	
	
	
	public void selectFirst(){
		this.selectedIndex = 0;
	}
	
	public void clearSelection(){
		this.selectedIndex = -1;
		loadData();
	}
	
	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
		loadData();
	}
	
	public int getSelectedIndex() {
		return selectedIndex;
	}
	
	public String[] getBancos(){
		return bancoService.getNomes();
	}
	
	public void setCodigo(String codigo) {
		this.codigo = codigo;
	}
	
	public String getCodigo() {
		return codigo;
	}
	
	public void setNome(String nome) {
		this.nome = nome;
	}
	
	public String getNome() {
		return nome;
	}
	
	public boolean existeBanco(){
		return bancoService.count() > 0;
	}
	
}